import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
import store from "@/store"

Vue.use(VueRouter)

// 先把VueRouter原型对象的push，先保存一份
let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;

// 重写push|replace 解决编程式导航多次点击后控制台报错的方法
// 第一个参数：告诉原来的push方法，跳转的路径
// 第二个参数：成功的回调
// 第三个参数：失败的回调
// call和apply的区别:
// 相同点：都可以调用函数一次，都可以篡改函数的上下文一次
// 不同点：call与apply传递参数的方式不同：call传递参数使用逗号隔开，apply方法执行，传递数组

VueRouter.prototype.push = function (location, resolve, reject) {
    if (resolve && reject) {
        originPush.call(this, location, resolve, reject);
    } else {
        originPush.call(this, location, () => { }, () => { });
    }
}

VueRouter.prototype.replace = function (location, resolve, reject) {
    if (resolve, reject) {
        originReplace.call(this.location, resolve, reject);
    } else {
        originPush.call(this, location, () => { }, () => { });
    }
}

let router = new VueRouter({
    routes,
    // 路由跳转后滚动条在最上方
    scrollBehavior(to, from, savedPosition) {
        return { y: 0 }
    },
    mode:"hash"
})

router.beforeEach(async (to, from, next) => {
    let token = store.state.user.token
    let name = store.state.user.userInfo.name
    if (token) {
        if (to.path == '/login') {
            next('/home')
        } else {
            if (name) {
                next()
            } else {
                try {
                    await store.dispatch('getUserInfo')
                    next()
                } catch (error) {
                    // token失效了
                    await store.dispatch('userLogout')
                    next('/login')
                }
            }
        }
    } else {
        if(to.path == '/shopcart' || to.path == '/trade' || to.path == '/pay' || to.path == '/paysucess' || to.path == '/addcartsucess' || to.path == '/center/myorder' || to.path == '/center/grouporder') {
            next('/login');
        } else {
            next();
        }
    }
})

export default router;